package prototype.controller.dictionary;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import prototype.constant.EMessageConst;
import prototype.constant.UrlConst;
import prototype.constant.data.DictionaryConst;
import prototype.controller.AbstractController;
import prototype.data.Dictionary;
import prototype.exception.ObjectFieldException;
import prototype.exception.ObjectNotUniqueException;
import prototype.model.DictionaryModel;

import javax.persistence.EntityManager;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;

/**
 * Обновление записи в словаре
 */
@WebServlet("/" + UrlConst.URL_DICTIONARY_UPDATE)
public class DictionaryUpdateController extends AbstractController {
	public static final String URL = UrlConst.URL_DICTIONARY_UPDATE;

	@Override
	protected JsonObject execute(EntityManager entityManager, HttpSession session, JsonElement requestData) throws Exception {
		final JsonObject dictionaryJson = requestData.getAsJsonObject().get("dictionary").getAsJsonObject();
		final Dictionary dictionary = new Dictionary(dictionaryJson);

		if (dictionary.getId() == null)
			throw new ObjectFieldException(EMessageConst.MISSING_OBJECT_ID, dictionary.getObjectType(), null, null, DictionaryConst.S_ID);
		if (dictionary.getLanguage() == null)
			throw new ObjectFieldException(EMessageConst.MISSING_DICTIONARY_LANGUAGE, dictionary.getObjectType(), null, dictionary.getId(), DictionaryConst.S_LANGUAGE);
		if (dictionary.getCode() == null)
			throw new ObjectFieldException(EMessageConst.MISSING_DICTIONARY_CODE, dictionary.getObjectType(), null, dictionary.getId(), DictionaryConst.S_CODE);
		if (dictionary.getText() == null || dictionary.getText().isEmpty())
			throw new ObjectFieldException(EMessageConst.MISSING_DICTIONARY_TEXT, dictionary.getObjectType(), null, dictionary.getId(), DictionaryConst.S_TEXT);

		Dictionary oldDic = DictionaryModel.select(entityManager, dictionary.getLanguage(), dictionary.getCode());
		if (oldDic != null && !oldDic.getId().equals(dictionary.getId()))
			throw new ObjectNotUniqueException(dictionary.getObjectType(), null, dictionary.getId(), null, oldDic.getId());

		entityManager.getTransaction().begin();
		entityManager.merge(dictionary);
		entityManager.getTransaction().commit();

		final JsonObject jsonObject = new JsonObject();
		return jsonObject;
	}
}
